<template>
  <view class="product-detail">
    <!-- 返回按钮 -->
    <view class="back-btn" @tap="goBack">
      <text class="iconfont icon-back"></text>
    </view>
    
    <!-- 商品图片轮播 -->
    <view class="swiper-container">
      <swiper
        class="product-swiper"
        circular
        autoplay
        :indicator-dots="false"
        :interval="4000"
        @change="onSwiperChange"
      >
        <swiper-item
          v-for="(image, index) in productData.gallery"
          :key="index"
          class="swiper-item"
        >
          <image
            :src="image"
            mode="aspectFill"
            class="product-image"
            @click="previewImage(productData.gallery, index)"
            :lazy-load="true"
          />
        </swiper-item>
      </swiper>
      
      <!-- 图片指示器 -->
      <view class="indicator-counter" v-if="productData.gallery && productData.gallery.length">
        <text>{{ currentImageIndex + 1 }}/{{ productData.gallery.length }}</text>
      </view>
    </view>

    <!-- 内容区域 -->
    <view class="content-container">
      <!-- 商品信息 -->
      <view class="product-info">
        <view class="product-name">{{ productData.name }}</view>

        <!-- <view
          class="product-tags"
          v-if="productData.keywords && productData.keywords.length"
        >
          <text
            v-for="(tag, index) in productData.keywords"
            :key="index"
            class="tag"
            >{{ tag }}</text
          >
        </view> -->
      </view>

      <!-- 规格选择 -->
      <view class="spec-section" v-if="productData.isMultipleSpec">
        <view class="spec-list">
          <view
            class="spec-group"
            v-for="(spec, index) in specifications"
            :key="index"
          >
            <text class="spec-name">{{ spec.name }}</text>
            <view class="spec-values">
              <view
                class="spec-value"
                :class="{ active: value.selected }"
                v-for="value in spec.valueList"
                :key="value.id"
                @tap="changeSpecSelected(spec.name, value)"
              >
                <text>{{ value.value }}</text>
                <text v-if="value.price > 0" class="value-price"
                  >+¥{{ value.price }}</text
                >
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 商品详情区域 -->
      <view class="detail-section" v-if="productData.brief">
        <view class="section-header">
          <text class="section-title">商品详情</text>
        </view>

        <view class="detail-content">
          <view class="detail-item">
            <view class="detail-text">{{ productData.brief }}</view>
          </view>
        </view>
      </view>

      <!-- 常见问题 -->
      <view class="faq-section" v-if="issues && issues.length">
        <view class="section-header">
          <text class="section-title">常见问题</text>
        </view>

        <view class="faq-list">
          <view v-for="(item, index) in issues" :key="index" class="faq-item">
            <view class="question">
              <text class="q-text">{{ item.question }}</text>
            </view>
            <view class="answer">
              <text class="a-text">{{ item.answer }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 底部安全区域 -->
      <view class="safe-area-bottom"></view>
    </view>

    <!-- 底部操作栏 -->
    <view class="action-bar" :class="{ closed: isClosed }">
      <view class="price-container">
        <text class="symbol">¥</text>
        <text class="amount">{{ totalPrice }}</text>
      </view>

      <view class="action-btns">
        <button
          class="add-cart-btn"
          :disabled="isClosed"
          @tap="handleAddToCart"
        >
          加入购物车
        </button>

        <button class="buy-btn" :disabled="isClosed" @tap="handleBuyNow">
          {{ isClosed ? '休息中' : '立即购买' }}
        </button>
      </view>
    </view>

    <!-- 店铺休息遮罩 -->
    <view class="closed-overlay" v-if="isClosed">
      <view class="closed-content">
        <view class="closed-icon">
          <text class="iconfont icon-clock"></text>
        </view>
        <text class="closed-title">店铺休息中</text>
        <text class="closed-time">营业时间：09:00 - 21:00</text>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  name: 'ProductDetail',
  data() {
    return {
      productData: {
        gallery: [],
        keywords: [],
        name: '',
        brief: '',
        retailPrice: 0,
        isMultipleSpec: false
      },
      specifications: [],
      id: null,
      isClosed: false,
      issues: [],
      currentImageIndex: 0
    }
  },
  onLoad(options) {
    this.id = options.id
    this.getProductDetail()
    this.checkStoreStatus()
  },
  computed: {
    getProductSelectedSpecs() {
      if (this.productData.isMultipleSpec && this.specifications.length) {
        let specs = []
        this.specifications.forEach((spec) => {
          spec.valueList.forEach((value) => {
            if (value.selected) {
              specs.push(`${spec.name}:${value.value}`)
            }
          })
        })
        return specs.length ? specs.join('，') : ''
      }
      return ''
    },
    totalPrice() {
      if (!this.productData.isMultipleSpec) {
        return this.productData.retailPrice
          ? Number(this.productData.retailPrice).toFixed(2)
          : '0.00'
      }
      
      // 多规格商品价格计算
      let price = this.productData.retailPrice || 0
      if (this.specifications.length) {
        let additionalPrice = 0
        this.specifications.forEach((spec) => {
          spec.valueList.forEach((value) => {
            if (value.selected) {
              additionalPrice += Number(value.price || 0)
            }
          })
        })
        // 确保基础价格加上附加价格
        price = Number(price) + additionalPrice
      }
      
      return price > 0 ? price.toFixed(2) : '0.00'
    }
  },
  methods: {
    async getProductDetail() {
      try {
        const { data } = await this.$get(`goods/detail?id=${this.id}`)
        data.info.keywords = data.info.keywords ?? ''
        data.info.keywords = data.info.keywords
          ? data.info.keywords.split(',')
          : []
        this.productData = data.info
        this.specifications = data.specificationList
        this.issues = data.issue
        if (this.productData.isMultipleSpec) {
          this.specifications.forEach((spec) => {
            spec.valueList.forEach((value, index) => {
              this.$set(value, 'selected', index === 0)
            })
          })
        }
      } catch (error) {
        console.log(error)
      }
    },
    changeSpecSelected(specName, selectedValue) {
      this.specifications.forEach((spec) => {
        if (spec.name === specName) {
          spec.valueList.forEach((value) => {
            value.selected = value.id === selectedValue.id
          })
        }
      })
    },
    previewImage(images, index) {
      uni.previewImage({
        urls: images,
        current: index
      })
    },
    checkStoreStatus() {
      const now = new Date()
      const hour = now.getHours()
      // 营业时间： 9:00 - 21:00
      this.isClosed = hour < 9 || hour >= 21
    },
    _prepareOrderData() {
      if (this.isClosed) {
        return null
      }
      if (this.productData.isMultipleSpec && !this.getProductSelectedSpecs) {
        uni.showToast({
          title: '请选择商品规格',
          icon: 'none'
        })
        return null
      }

      let specificationIds = []
      if (this.productData.isMultipleSpec && this.specifications.length) {
        this.specifications.forEach((spec) => {
          spec.valueList.forEach((value) => {
            if (value.selected) {
              specificationIds.push(value.id)
            }
          })
        })
      }

      // 确保价格有效
      const price = Number(this.totalPrice) || this.productData.retailPrice || 0
      if (price <= 0) {
        uni.showToast({
          title: '商品价格有误',
          icon: 'none'
        })
        return null
      }

      return {
        specificationIds,
        price
      }
    },
    handleBuyNow() {
      const orderData = this._prepareOrderData()
      if (!orderData) return

      const productInfo = {
        name: this.productData.name,
        price: orderData.price * 100,
        freight: 0,
        image: this.productData.gallery[0],
        number: this.productData.number,
        specs: this.getProductSelectedSpecs,
        specificationIds: orderData.specificationIds,
        goodsId: this.id,
        productId: this.productData.id
      }
      uni.navigateTo({
        url:
          '/pages/pay/index?productInfo=' +
          encodeURIComponent(JSON.stringify(productInfo))
      })
    },

    handleAddToCart() {
      const orderData = this._prepareOrderData()
      if (!orderData) return

      // 确保商品数量有效
      const productNumber = this.productData.number || 1
      
      const cartData = {
        goodsId: this.id,
        goodsName: this.productData.name,
        number: productNumber,
        specificationsList: this.getProductSelectedSpecs
          ? this.getProductSelectedSpecs.split('，')
          : [],
        specificationIds: orderData.specificationIds,
        price: orderData.price * productNumber
      }
      this.$post('cart/add', cartData)
        .then((res) => {
          if (res.errno === 0) {
            uni.showToast({
              title: '已加入购物车',
              icon: 'success'
            })
          } else {
            uni.showToast({
              title: res.errmsg || '加入购物车失败',
              icon: 'none'
            })
          }
        })
        .catch((err) => {
          console.error('加入购物车失败', err)
          uni.showToast({
            title: '加入购物车失败',
            icon: 'none'
          })
        })
    },
    onSwiperChange(e) {
      this.currentImageIndex = e.detail.current
    },
    goBack() {
      uni.navigateBack()
    },
    navigateToCart() {
      uni.switchTab({
        url: '/pages/cart/index'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
// 变量定义
$primary-color: #000000;
$secondary-color: #efefef;
$text-primary: #222222;
$text-secondary: #555555;
$text-light: #888888;
$background-color: #ffffff;
$border-color: #eeeeee;
$disabled-color: #cccccc;

// 商品详情页主容器
.product-detail {
  position: relative;
  min-height: 100vh;
  background-color: $background-color;
}

// 返回按钮
.back-btn {
  position: fixed;
  left: 20rpx;
  top: 60rpx;
  width: 80rpx;
  height: 80rpx;
  background: rgba(255, 255, 255, 0.85);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 100;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.15);
  backdrop-filter: blur(5px);

  &::before {
    content: "";
    display: block;
    width: 24rpx;
    height: 24rpx;
    border-left: 3rpx solid $primary-color;
    border-bottom: 3rpx solid $primary-color;
    transform: rotate(45deg);
    margin-right: -6rpx;
  }

  .icon-back {
    color: $primary-color;
    font-size: 40rpx;
  }
}

// 商品轮播
.swiper-container {
  position: relative;
  width: 100%;
  height: 750rpx;
}

.product-swiper {
  width: 100%;
  height: 100%;

  .swiper-item {
    width: 100%;
    height: 100%;
  }

  .product-image {
    width: 100%;
    height: 100%;
  }
}

.indicator-counter {
  position: absolute;
  right: 30rpx;
  bottom: 30rpx;
  background: rgba(0, 0, 0, 0.5);
  padding: 6rpx 20rpx;
  border-radius: 30rpx;
  z-index: 10;
  
  text {
    color: white;
    font-size: 24rpx;
    font-weight: 500;
  }
}

// 内容容器
.content-container {
  position: relative;
  padding: 30rpx 30rpx 120rpx;
  background: $background-color;
  min-height: 60vh;
}

// 商品信息
.product-info {
  display: flex;
  gap: 10px;
  align-items: center;
  margin-bottom: 40rpx;
  border-bottom: 1px solid $border-color;

  .product-name {
    font-size: 36rpx;
    font-weight: 800;
    color: $text-primary;
    margin-bottom: 16rpx;
    line-height: 1.4;
  }

  .product-tags {
    display: flex;
    flex-wrap: wrap;

    .tag {
      background: $secondary-color;
      color: $text-secondary;
      font-size: 24rpx;
      padding: 6rpx 16rpx;
      margin-right: 16rpx;
      margin-bottom: 16rpx;
    }
  }
}

// 规格选择区域
.spec-section {
  padding: 0 0 40rpx;
  border-bottom: 1px solid $secondary-color;


  .section-header {
    margin-bottom: 20rpx;

    .section-title {
      font-size: 30rpx;
      font-weight: normal;
      color: $text-primary;
    }
  }

  .spec-list {
    .spec-group {
      margin-bottom: 24rpx;

      .spec-name {
        font-size: 28rpx;
        color: $text-secondary;
        margin-bottom: 16rpx;
        display: block;
      }

      .spec-values {
        display: flex;
        flex-wrap: wrap;
        gap: 16rpx;

        .spec-value {
          padding: 12rpx 24rpx;
          background: $secondary-color;
          font-size: 26rpx;
          color: $text-secondary;
          border: 1px solid transparent;

          &.active {
            color: #fff;
            background-color: #000;
            border-color: $primary-color;

            .value-price {
              color: #fff;
            }
          }

          .value-price {
            font-size: 24rpx;
            color: $text-light;
            margin-left: 8rpx;
          }
        }
      }
    }
  }
}

// 商品详情区域
.detail-section {
  padding: 30rpx 0;
  border-bottom: 1px solid $secondary-color;

  .section-header {
    margin-bottom: 20rpx;

    .section-title {
      font-size: 30rpx;
      font-weight: normal;
      color: $text-primary;
    }
  }

  .detail-content {
    .detail-item {
      margin-bottom: 20rpx;

      .detail-text {
        font-size: 28rpx;
        color: $text-secondary;
        line-height: 1.6;
      }
    }
  }
}

// 常见问题区域
.faq-section {
  padding: 30rpx 0;

  .section-header {
    margin-bottom: 30rpx;

    .section-title {
      font-size: 30rpx;
      font-weight: normal;
      color: $text-primary;
    }
  }

  .faq-list {
    .faq-item {
      margin-bottom: 30rpx;

      &:last-child {
        margin-bottom: 0;
      }

      .question {
        margin-bottom: 10rpx;

        .q-text {
          font-size: 28rpx;
          color: $text-primary;
          font-weight: 500;
          line-height: 1.5;
        }
      }

      .answer {
        .a-text {
          font-size: 26rpx;
          color: $text-secondary;
          line-height: 1.6;
        }
      }
    }
  }
}

// 底部操作栏
.action-bar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background: $background-color;
  border-top: 1px solid $border-color;
  display: flex;
  align-items: center;
  padding-bottom: calc(env(safe-area-inset-bottom));
  z-index: 90;

  &.closed {
    .add-cart-btn,
    .buy-btn {
      opacity: 0.5;
    }
  }

  .price-container {
    padding: 0 20rpx;

    .symbol {
      font-size: 24rpx;
      color: $primary-color;
    }

    .amount {
      font-size: 36rpx;
      color: $primary-color;
      font-weight: bold;
    }
  }

  .action-btns {
    flex: 1;
    display: flex;
    height: 100%;
    padding: 16rpx 20rpx;

    button {
      flex: 1;
      height: 72rpx;
      margin: 0;
      font-size: 28rpx;
      font-weight: normal;
      display: flex;
      align-items: center;
      justify-content: center;

      &:disabled {
        opacity: 0.7;
      }
    }

    .add-cart-btn {
      background: $secondary-color;
      color: $primary-color;
      margin-right: 16rpx;
    }

    .buy-btn {
      background: $primary-color;
      color: white;
    }
  }
}

// 底部安全区域
.safe-area-bottom {
  height: 120rpx;
}

// 店铺休息遮罩
.closed-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  backdrop-filter: blur(5px);
  z-index: 999;
  display: flex;
  align-items: center;
  justify-content: center;

  .closed-content {
    text-align: center;

    .closed-icon {
      width: 100rpx;
      height: 100rpx;
      background: rgba(255, 255, 255, 0.2);
      display: flex;
      align-items: center;
      justify-content: center;
      margin: 0 auto 30rpx;

      .iconfont {
        font-size: 60rpx;
        color: white;
      }
    }

    .closed-title {
      font-size: 36rpx;
      font-weight: normal;
      color: white;
      margin-bottom: 16rpx;
    }

    .closed-time {
      font-size: 28rpx;
      color: rgba(255, 255, 255, 0.8);
    }
  }
}
</style>
